package com.acme.bankapp.domain.bank;

import com.acme.bankapp.exceptions.bank.ClientsExistsException;
import com.acme.bankapp.service.bank.EmailService;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Bank implements Serializable {
    private List<Client> clients;
    private List<ClientRegistrationListener> listeners;
    private EmailService service = new EmailService();

    private class PrintClientListener implements ClientRegistrationListener, Serializable{
        public void onClientAdded(Client c) {
            System.out.println(c);
        }
    }

    @SuppressWarnings("UnusedDeclaration")
    private class EmailNotificationListener implements ClientRegistrationListener, Serializable {
        public void onClientAdded(Client c) {
            Email email = new Email("client@example.com", c);
            service.sendNotificationEmail(email);

        }
    }

    @SuppressWarnings("UnusedDeclaration")
    private class DebugListener implements ClientRegistrationListener, Serializable {
        public void onClientAdded(Client c) {
            System.out.println(String.format("Debug! Client: %s, Date: %s", c, new Date()));
        }
    }

    public Bank() {
        super();
        clients = new ArrayList<Client>();
        listeners = new ArrayList<ClientRegistrationListener>();
        listeners.add(new EmailNotificationListener());
    }

    @SuppressWarnings("UnusedDeclaration")
    public Bank(List<ClientRegistrationListener> listeners) {
        this();
        for (ClientRegistrationListener listener: listeners) {
            addClientRegListener(listener);
        }
    }

    public Client addClient(Client client) throws ClientsExistsException {
        for (Client c : clients) {
            if (c.equals(client)) {
                throw new ClientsExistsException();
            }
        }
        clients.add(client);
        for (ClientRegistrationListener listener : listeners) {
            listener.onClientAdded(client);
        }
        return client;
    }

    public List<Client> getClients() {
        return new ArrayList<Client>(clients);
    }

    public void addClientRegListener(ClientRegistrationListener listener) {
        listeners.add(listener);
    }

    public void stopAllServices() {
        service.close();
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder("Bank with clients:\n");
        for (Client c : clients) {
            builder.append(c.toString() + "\n");
        }
        return builder.toString();
    }
}
